<template>
  <el-dialog :title="managerTitle" :visible.sync="visible" :fullscreen="true" :close-on-click-modal="false"
    :close-on-press-escape="false" v-loading="addOrUpdateloading" append-to-body>
    <div>
      <el-row>
        <el-col :span="4">
          <el-row>
            <div class="nodeContent" v-infinite-scroll="load" :infinite-scroll-disabled="isLoading || !hasMore"
              :infinite-scroll-delay="200"> <!-- 增加200ms防抖 -->
              <el-card class="box-card" v-for="(item, index) in nodeDataList" :key="'node_'+item.id"
                :class="{ 'selected-card': item.id === selectedNodeId }">
                <div slot="header" class="clearfix">
                  <el-button class="el-icon-info" type="text" @click="loadContent(item)"></el-button>
                  <el-button class="el-icon-upload2" type="text" @click="setUp(item)"></el-button>
                  <el-button class="el-icon-download" type="text" @click="setDown(item)"></el-button>
                  <el-button class="el-icon-edit" v-if="nodeType==1" type="text"
                    @click="handleUpdate(item)"></el-button>
                  <el-button class="el-icon-delete" v-if="nodeType==1" type="text"
                    @click="handleDelete(item)"></el-button>
                </div>
                <div class="box-content" @click="loadContent(item)">
                  {{item.nodeName }}
                </div>
              </el-card>
            </div>
            <el-row :gutter="10" class="mb8" v-if="nodeType==1">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增节点</el-button>
              </el-col>
            </el-row>
          </el-row>
        </el-col>
        <el-col :span="20" v-show="contenFlag">
          <SubjectContent ref="subjectContentRef"></SubjectContent>
        </el-col>
      </el-row>
      <el-row>
        <!-- 添加或修改(教育)绘本节点对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="节点名称" prop="nodeName">
              <el-input v-model="form.nodeName" placeholder="请输入节点名称" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm" :loading="submitLoading">
              {{ submitLoading ? '提交中...' : '确定' }}</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-row>
    </div>
  </el-dialog>
</template>
<script>
  import {
    isEmpty
  } from "@/utils/validate"
  import {
    listNode,
    getNode,
    delNode,
    addNode,
    updateNode,
    setNodeSortNo
  } from "@/api/bus_web/course/node";
  import SubjectContent from "../content/index.vue";
  export default {
    name: "NodeSet",
    components: {
      SubjectContent
    },
    data() {
      return {
        isLoading: false, // 是否正在加载中
        hasMore: true, // 是否还有更多数据
        contenFlag: false, //显示题目列表
        selectedNodeId: null,
        visible: false,
        nodeType: null,
        pictureBookId: null,
        pNodeId: null,
        submitLoading: false,
        managerTitle: '',
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 课程管理表格数据
        nodeDataList: [],
        addOrUpdateloading: true,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          pictureBookId: null,
          nodeType: null
        },
        // 表单参数
        form: {
          pictureBookId: null,
          nodeType: null
        },
        // 表单校验
        rules: {
          nodeName: [{
            required: true,
            message: "节点名称不能为空",
            trigger: "blur"
          }]
        }
      };
    },
    created() {
      // this.resetPage();
    },
    mounted() {
      // 改为在 mounted 中手动触发首次加载
      // this.load();
    },
    methods: {

      //初始化数据
      init(id, nodeType, pNodeId, title) {
        this.reset()
        this.visible = true
        this.addOrUpdateloading = true
        this.managerTitle = title
        this.pictureBookId = id
        this.nodeType = nodeType

        this.queryParams.nodeType = this.nodeType
        this.queryParams.pictureBookId = this.pictureBookId
        this.pNodeId = pNodeId
        if (2 == this.nodeType) {
          this.queryParams.pNodeId = pNodeId
          this.form.pNodeId = pNodeId
        }
        this.form.nodeType = this.nodeType
        this.form.pictureBookId = this.pictureBookId
        this.nodeDataList = []
        this.isLoadin = false
        this.hasMore = true
        this.contenFlag = false
        this.load()
      },

      resetPage() {
        this.queryParams.pageNum = 1;
        this.nodeDataList = [];
        this.hasMore = true;
      },
      getList() {
        this.loading = true;
        listNode(this.queryParams).then(response => {
          this.nodeDataList.push(...response.rows);
          this.total = response.total;
          // 判断是否还有更多数据
          if (response.rows.length < this.queryParams.pageSize || this.nodeDataList.length >= this.total) {
            this.hasMore = false;
          } else {
            this.queryParams.pageNum += 1; // 递增页码
          }
          this.addOrUpdateloading = false
        }).finally(() => {
          this.loading = false;
          this.isLoading = false; // 重置加载状态
        });
      },
      //无限加载
      load() {

        if (this.isLoading || !this.hasMore) return;
        this.isLoading = true;
        this.getList();
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          pictureBookId: null,
          nodeType: null,
          nodeName: null,
          sortNo: null,
          gmtCreate: null,
          gmtModify: null,
          deleted: null,
          createBy: null,
          updateBy: null
        };
        this.resetForm("form");
        this.form.nodeType = this.nodeType
        this.form.pictureBookId = this.pictureBookId
        if (2 == this.nodeType) {
          this.queryParams.pNodeId = this.pNodeId
          this.form.pNodeId = this.pNodeId
        }
      },
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加绘本节点";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getNode(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改绘本节点";
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除节点编号为"' + ids + '"的数据项？').then(function() {
          return delNode(ids);
        }).then(() => {
          // this.getList();

          // 从前端列表中直接过滤掉被删除项
          this.nodeDataList = this.nodeDataList.filter(item => item.id !== row.id);
          this.total--; // 总数量减1
          this.$modal.msgSuccess("删除成功");

          // 如果当前页数据已空且还有更多数据，自动加载前一页
          if (this.nodeDataList.length === 0 && this.hasMore) {
            this.queryParams.pageNum = Math.max(1, this.queryParams.pageNum - 1);
            this.getList();
          }

        }).catch(() => {});
      },

      submitForm() {
        this.submitLoading = true
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateNode(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                // 查找并更新对应节点
                const index = this.nodeDataList.findIndex(item => item.id === response.data.id);
                if (index > -1) {
                  this.nodeDataList.splice(index, 1, response.data);
                }
              }).finally(() => {
                this.submitLoading = false
              })
            } else {
              addNode(this.form).then(response => {
                this.nodeDataList.push(response.data);
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                // 维护分页状态
                this.total++;
                this.queryParams.pageNum = Math.ceil(this.total / this.queryParams.pageSize);
              }).finally(() => {
                this.submitLoading = false
              })
            }
          } else {
            this.submitLoading = false
          }
        });
      },
      //加载题目内容列表
      loadContent(row) {
        this.contenFlag = true
        this.selectedNodeId = row.id
        this.$refs.subjectContentRef.init(row.id)
      },
      // 上升高
      setUp(row) {
        this.selectedNodeId = row.id
        const index = this.nodeDataList.findIndex(item => item.id === row.id);
        if (index > -1) {
          if (index > 0) {
            // 与前一个元素交换
            const newList = [...this.nodeDataList]; // 创建副本
            const temp = newList[index];
            newList[index] = newList[index - 1];
            newList[index - 1] = temp;
            setNodeSortNo(newList.map(item => item.id)).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.nodeDataList = newList; // 重新赋值以触发更新
            });

          }
        }
      },
      // 下降
      setDown(row) {
        this.selectedNodeId = row.id
        const index = this.nodeDataList.findIndex(item => item.id === row.id);
        if (index > -1 && index < this.nodeDataList.length - 1) {
          const newList = [...this.nodeDataList]; // 创建副本
          const temp = newList[index];
          newList[index] = newList[index + 1];
          newList[index + 1] = temp;
          setNodeSortNo(newList.map(item => item.id)).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.nodeDataList = newList; // 重新赋值以触发更新
          });
        }

      }
    }
  };
</script>
<style scoped>
  .nodeContent {
    border: 0px blue solid;
    width: 100%;
    height: calc(100vh - 160px);
    /* 根据实际布局调整 */
    overflow-y: auto;
    padding-right: 8px;
    /* 防止滚动条遮挡内容 */
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .box-card {
    width: 100%;
    height: 22vh;
    margin-bottom: 2vh;
    cursor: pointer;
  }

  .box-content {
    width: 100%;
    line-height: 24px;
    /* 可根据需要调整 */
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    /* 文字居中显示 */
    padding: 8px;
    box-sizing: border-box;
    word-break: break-all;
    /* 必要时强制断词 */
    white-space: pre-wrap;
    /* 支持手动换行（如 \n）并允许自动换行 */
    overflow: hidden;
  }

  .clearfix {
    text-align: right;
    /* 确保标题栏内的内容右对齐 */
  }

  .selected-card {
    /* 浅灰色背景 */
    border: 1px solid green;
    /* 可以加个边框强调选中状态 */
  }
</style>
